"""
教学风格分析器
"""
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple, Any
from uuid import uuid4
from collections import defaultdict
from enum import Enum

from ai_services.teaching_quality_assessment.teaching_quality_service import (
    TeachingStyle, TeacherBehaviorData, InteractionData, TeachingStyleAnalysis
)


class TeachingStyleAnalyzer:
    """教学风格分析器"""
    
    def __init__(self):
        self.style_patterns = {
            TeachingStyle.AUTHORITATIVE: {
                'lecturing': 0.6, 'questioning': 0.2, 'demonstrating': 0.1, 'interacting': 0.1
            },
            TeachingStyle.INTERACTIVE: {
                'interacting': 0.4, 'questioning': 0.3, 'lecturing': 0.2, 'observing': 0.1
            },
            TeachingStyle.DEMONSTRATIVE: {
                'demonstrating': 0.5, 'lecturing': 0.3, 'interacting': 0.2
            },
            TeachingStyle.COLLABORATIVE: {
                'interacting': 0.5, 'observing': 0.2, 'questioning': 0.2, 'lecturing': 0.1
            },
            TeachingStyle.INQUIRY_BASED: {
                'questioning': 0.4, 'interacting': 0.3, 'observing': 0.2, 'lecturing': 0.1
            }
        }
    
    def analyze_teaching_style(self, teacher_id: str, 
                             behavior_history: List[TeacherBehaviorData],
                             interaction_history: List[InteractionData]) -> TeachingStyleAnalysis:
        """分析教学风格"""
        analysis_id = str(uuid4())
        
        # 分析行为分布
        behavior_distribution = self._analyze_behavior_distribution(behavior_history)
        
        # 分析互动模式
        interaction_patterns = self._analyze_interaction_patterns(interaction_history)
        
        # 识别教学风格
        teaching_style, style_confidence = self._identify_teaching_style(
            behavior_distribution, interaction_patterns
        )
        
        # 识别优势
        strengths = self._identify_strengths(teaching_style, behavior_distribution, interaction_patterns)
        
        # 识别改进领域
        improvement_areas = self._identify_improvement_areas(
            teaching_style, behavior_distribution, interaction_patterns
        )
        
        # 生成建议
        recommendations = self._generate_recommendations(
            teaching_style, strengths, improvement_areas
        )
        
        return TeachingStyleAnalysis(
            analysis_id=analysis_id,
            teacher_id=teacher_id,
            teaching_style=teaching_style,
            style_confidence=style_confidence,
            behavior_distribution=behavior_distribution,
            interaction_patterns=interaction_patterns,
            strengths=strengths,
            improvement_areas=improvement_areas,
            recommendations=recommendations
        )
    
    def _analyze_behavior_distribution(self, behavior_history: List[TeacherBehaviorData]) -> Dict[str, float]:
        """分析行为分布"""
        if not behavior_history:
            return {}
        
        behavior_counts = defaultdict(int)
        total_behaviors = len(behavior_history)
        
        for behavior_data in behavior_history:
            behavior_counts[behavior_data.behavior.value] += 1
        
        # 计算比例
        behavior_distribution = {}
        for behavior, count in behavior_counts.items():
            behavior_distribution[behavior] = count / total_behaviors
        
        return behavior_distribution
    
    def _analyze_interaction_patterns(self, interaction_history: List[InteractionData]) -> Dict[str, Any]:
        """分析互动模式"""
        if not interaction_history:
            return {}
        
        # 互动频率
        interaction_frequency = len(interaction_history)
        
        # 平均互动时长
        avg_duration = np.mean([interaction.duration for interaction in interaction_history])
        
        # 互动质量分布
        quality_counts = defaultdict(int)
        for interaction in interaction_history:
            quality_counts[interaction.interaction_quality.value] += 1
        
        quality_distribution = {}
        for quality, count in quality_counts.items():
            quality_distribution[quality] = count / len(interaction_history)
        
        # 平均参与度和有效性
        avg_engagement = np.mean([interaction.engagement_score for interaction in interaction_history])
        avg_effectiveness = np.mean([interaction.effectiveness_score for interaction in interaction_history])
        
        # 提问统计
        total_questions = sum(interaction.teacher_question_count for interaction in interaction_history)
        total_responses = sum(interaction.student_response_count for interaction in interaction_history)
        
        return {
            'interaction_frequency': interaction_frequency,
            'avg_duration': avg_duration,
            'quality_distribution': quality_distribution,
            'avg_engagement': avg_engagement,
            'avg_effectiveness': avg_effectiveness,
            'total_questions': total_questions,
            'total_responses': total_responses,
            'question_response_ratio': total_responses / total_questions if total_questions > 0 else 0
        }
    
    def _identify_teaching_style(self, behavior_distribution: Dict[str, float],
                               interaction_patterns: Dict[str, Any]) -> Tuple[TeachingStyle, float]:
        """识别教学风格"""
        if not behavior_distribution:
            return TeachingStyle.MIXED, 0.5
        
        # 计算与各种风格的匹配度
        style_scores = {}
        
        for style, pattern in self.style_patterns.items():
            score = 0
            for behavior, expected_ratio in pattern.items():
                actual_ratio = behavior_distribution.get(behavior, 0)
                # 使用余弦相似度计算匹配度
                score += min(actual_ratio, expected_ratio)
            
            # 互动模式加成
            if interaction_patterns:
                interaction_bonus = self._calculate_interaction_bonus(style, interaction_patterns)
                score += interaction_bonus * 0.3
            
            style_scores[style] = score
        
        # 找到最匹配的风格
        best_style = max(style_scores.items(), key=lambda x: x[1])
        
        # 计算置信度
        max_score = best_style[1]
        second_max = sorted(style_scores.values(), reverse=True)[1] if len(style_scores) > 1 else 0
        confidence = (max_score - second_max) / max_score if max_score > 0 else 0.5
        
        # 如果置信度太低，归类为混合型
        if confidence < 0.3:
            return TeachingStyle.MIXED, confidence
        
        return best_style[0], confidence
    
    def _calculate_interaction_bonus(self, style: TeachingStyle, 
                                   interaction_patterns: Dict[str, Any]) -> float:
        """计算互动模式加成"""
        bonus = 0
        
        avg_engagement = interaction_patterns.get('avg_engagement', 50)
        avg_effectiveness = interaction_patterns.get('avg_effectiveness', 50)
        question_response_ratio = interaction_patterns.get('question_response_ratio', 0)
        
        if style == TeachingStyle.INTERACTIVE:
            bonus += (avg_engagement / 100) * 0.5
            bonus += (question_response_ratio * 0.3)
        elif style == TeachingStyle.INQUIRY_BASED:
            bonus += (question_response_ratio * 0.6)
        elif style == TeachingStyle.COLLABORATIVE:
            bonus += (avg_engagement / 100) * 0.4
            bonus += (avg_effectiveness / 100) * 0.3
        elif style == TeachingStyle.AUTHORITATIVE:
            if avg_engagement < 60:  # 权威型可能参与度较低
                bonus += 0.2
        
        return bonus
    
    def _identify_strengths(self, teaching_style: TeachingStyle,
                          behavior_distribution: Dict[str, float],
                          interaction_patterns: Dict[str, Any]) -> List[str]:
        """识别优势"""
        strengths = []
        
        # 基于教学风格的优势
        style_strengths = {
            TeachingStyle.AUTHORITATIVE: ["知识传授能力强", "课堂控制力好", "内容讲解清晰"],
            TeachingStyle.INTERACTIVE: ["师生互动频繁", "课堂氛围活跃", "学生参与度高"],
            TeachingStyle.DEMONSTRATIVE: ["演示能力强", "实践教学丰富", "直观教学效果好"],
            TeachingStyle.COLLABORATIVE: ["协作学习引导好", "团队合作能力强", "学生自主性培养"],
            TeachingStyle.INQUIRY_BASED: ["启发式教学", "培养学生思维能力", "问题导向教学"],
            TeachingStyle.MIXED: ["教学方法多样化", "适应性强", "灵活运用各种策略"]
        }
        
        strengths.extend(style_strengths.get(teaching_style, []))
        
        # 基于行为分布的优势
        if behavior_distribution.get('demonstrating', 0) > 0.3:
            strengths.append("演示教学能力突出")
        
        if behavior_distribution.get('questioning', 0) > 0.25:
            strengths.append("善于提问引导学生思考")
        
        if behavior_distribution.get('interacting', 0) > 0.3:
            strengths.append("师生互动能力强")
        
        # 基于互动模式的优势
        if interaction_patterns:
            if interaction_patterns.get('avg_engagement', 0) > 75:
                strengths.append("学生参与度高")
            
            if interaction_patterns.get('avg_effectiveness', 0) > 80:
                strengths.append("教学效果显著")
            
            if interaction_patterns.get('question_response_ratio', 0) > 0.7:
                strengths.append("问答互动效果好")
        
        return list(set(strengths))  # 去重
    
    def _identify_improvement_areas(self, teaching_style: TeachingStyle,
                                  behavior_distribution: Dict[str, float],
                                  interaction_patterns: Dict[str, Any]) -> List[str]:
        """识别改进领域"""
        improvement_areas = []
        
        # 基于行为分布的改进建议
        if behavior_distribution.get('interacting', 0) < 0.15:
            improvement_areas.append("增加师生互动环节")
        
        if behavior_distribution.get('questioning', 0) < 0.1:
            improvement_areas.append("增加提问频率")
        
        if behavior_distribution.get('demonstrating', 0) < 0.05:
            improvement_areas.append("增加演示教学")
        
        # 基于互动模式的改进建议
        if interaction_patterns:
            if interaction_patterns.get('avg_engagement', 0) < 60:
                improvement_areas.append("提高学生参与度")
            
            if interaction_patterns.get('avg_effectiveness', 0) < 70:
                improvement_areas.append("提升教学效果")
            
            if interaction_patterns.get('question_response_ratio', 0) < 0.3:
                improvement_areas.append("改善问答互动质量")
        
        # 基于教学风格的特定改进建议
        if teaching_style == TeachingStyle.AUTHORITATIVE:
            if behavior_distribution.get('interacting', 0) < 0.2:
                improvement_areas.append("增加学生参与机会")
        elif teaching_style == TeachingStyle.INTERACTIVE:
            if behavior_distribution.get('lecturing', 0) < 0.1:
                improvement_areas.append("适当增加知识讲解")
        
        return improvement_areas
    
    def _generate_recommendations(self, teaching_style: TeachingStyle,
                                strengths: List[str], improvement_areas: List[str]) -> List[str]:
        """生成建议"""
        recommendations = []
        
        # 基于优势的建议
        if "师生互动能力强" in strengths:
            recommendations.append("继续保持良好的互动教学，可以尝试更多样化的互动形式")
        
        if "演示教学能力突出" in strengths:
            recommendations.append("发挥演示教学优势，结合更多实际案例")
        
        # 基于改进领域的建议
        if "增加师生互动环节" in improvement_areas:
            recommendations.append("建议在课堂中增加小组讨论、问答环节等互动活动")
        
        if "增加提问频率" in improvement_areas:
            recommendations.append("适当增加课堂提问，引导学生主动思考")
        
        if "提高学生参与度" in improvement_areas:
            recommendations.append("设计更多参与性活动，鼓励学生积极发言")
        
        # 基于教学风格的通用建议
        style_recommendations = {
            TeachingStyle.AUTHORITATIVE: ["适当增加互动环节，平衡讲授与参与"],
            TeachingStyle.INTERACTIVE: ["保持互动优势，注意知识点的系统性讲解"],
            TeachingStyle.DEMONSTRATIVE: ["结合理论讲解，增强演示的教育效果"],
            TeachingStyle.COLLABORATIVE: ["引导学生合作学习，培养团队协作能力"],
            TeachingStyle.INQUIRY_BASED: ["设计层次化问题，引导学生深入思考"],
            TeachingStyle.MIXED: ["继续保持教学方法的多样性和灵活性"]
        }
        
        recommendations.extend(style_recommendations.get(teaching_style, []))
        
        return recommendations